package com.damage.supplier.oa.sendOrder;

import com.damage.common.entity.Order;
import com.damage.common.exception.IncorrectStateException;
import com.damage.common.oa.sendOrder.SendOrderConfig;
import com.damage.common.service.IPublicService;
import com.damage.supplier.service.IReceiveOrderService;
import com.sun.istack.internal.Nullable;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ConfirmOrderService {

    @Autowired
    private IPublicService publicService;

    @Autowired
    private IReceiveOrderService receiveOrderService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Transactional
    public Order confirmOrCancelOrder(String taskId, Boolean isCancel, @Nullable String comment){
        //关联业务实体
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        String businessKey = processInstance.getBusinessKey();
        Integer orderId = Integer.parseInt(businessKey);

        try {
            if (isCancel == true){
                //取消订单
                Integer cancelResult = receiveOrderService.cancelOrder(orderId);
                if (cancelResult == 0){
                    //取消订单操作无影响
                    return null;
                }
                taskService.setVariable(taskId, SendOrderConfig.CANCEL_ORDER,true);
                //添加评论
                StringBuffer sb = new StringBuffer();
                sb.append("订单取消原因:");
                sb.append(comment);
                taskService.addComment(taskId,processInstanceId,sb.toString());

            }else{
                //确认订单
                Integer confirmResult = receiveOrderService.confirmOrder(orderId);
                if (confirmResult == 0){
                    //确认订单操作无影响
                    return null;
                }
                taskService.setVariable(taskId, SendOrderConfig.CANCEL_ORDER,false);
            }
        } catch (IncorrectStateException e) {
            throw e;
        }
        taskService.complete(taskId);
        Order order = publicService.findOrderById(orderId);

        return order;
    }
}
